import React, { Fragment, useState } from 'react';
import { NavigateFunction, useNavigate } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { changeModalOpen, clearUserInfo } from '@/store/modules/userStore';
import { Button, Modal, Form, Input, FormProps, message, Dropdown, Space } from 'antd';
import type { MenuProps } from 'antd';
import Tips from '@/components/Header/components/Tips/Tips';
import logo from '../../assets/logo.png';
import { DownOutlined, LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginParams, UserInfo } from '@/type/userType';
import { getCodeAPI } from '@/api/userAPI/userAPI';
import { userLogin } from '@/store/modules/userStore';
import './Header.scss';
import useCountdown from '@/hooks/useCountdown';


const Header: React.MemoExoticComponent<() => React.ReactElement> = React.memo(() => {
  const navigate: NavigateFunction = useNavigate();
  const dispatch = useDispatch();
  const isModalOpen = useSelector((state: any) => state.userStore.isModalOpen);
  const userInfo: UserInfo = useSelector((state: any) => state.userStore.userInfo);
  const [form] = Form.useForm();
  const { start, countdown, subCountdown } = useCountdown();

  const [isLoginLoading, setIsLoginLoading] = useState<boolean>(false);
  const items: MenuProps['items'] = [
    {
      key: '1',
      label: (
        <span>实名认证</span>
      ),
    },
    {
      key: '2',
      label: (
        <span>挂号订单</span>

      ),
    },
    {
      key: '3',
      label: (
        <span>就诊人管理</span>
      ),
    },
    {
      key: '4',
      label: (
        <span>退出登录</span>
      ),
    },
  ];

  /**
   * @description 跳转到首页的回调函数
   * */
  const goToHome = () => {
    navigate('/');
  };


  /**
   *@description 对话框底部取消按钮的回调函数
   * */
  const handleCancel = () => {
    dispatch(changeModalOpen(false));
  };
  /**
   *@description 对话框完毕关闭的回调函数
   * */
  const afterClose = () => {
    form.setFields([{ name: 'phone', errors: undefined }, { name: 'code', errors: undefined }]);

  };

  /**
   * @description 点击登录按钮时的回调函数
   * */
  const handleLogin = () => {
    dispatch(changeModalOpen(true));
  };


  /**
   * @description 表单提交时候的回调函数
   * */
  const onFinish: FormProps<LoginParams>['onFinish'] = async (formData: LoginParams) => {
    try {
      setIsLoginLoading(true);
      await dispatch(userLogin(formData)).unwrap();
      dispatch(changeModalOpen(false));
      message.success('登录成功');
    } catch (error: any) {
      message.error(error.message);
    } finally {
      setIsLoginLoading(false);
    }
  };


  /**
   * @description 发送请求获取验证码的回调函数
   * */
  const getCode = async () => {
    const { outOfDate } = await form.validateFields(['phone']).catch(error => error);
    if (outOfDate === undefined) {
      try {
        subCountdown();
        const { data } = await getCodeAPI(form.getFieldsValue().phone);
        if (data === null) return message.error('验证码获取过于频繁');
        form.setFieldsValue({ code: data });
      } catch (error: any) {
        message.error(error.message);
      }
    }

  };

  const renderCountdown = () => {
    if (start) {
      return `${countdown}秒后重新发送`;
    } else {
      return '获取验证码';
    }

  };
  /**
   * @description 下拉菜单的点击事件
   * */
  const onClick: MenuProps['onClick'] = async ({ key }) => {
    if (key === '1') {
      navigate('/member/user');
    } else if (key === '2') {
      navigate('/member/orderList');
    } else if (key === '3') {
      navigate('/member/patient');
    } else {
      dispatch(clearUserInfo());
    }
  };


  const isLogin = () => {
    if (!userInfo.token) {
      return (
        <>
          <span onClick={handleLogin}>登录-注册</span>
        </>
      );
    } else {
      return (
        <div>
          <Dropdown menu={{ items, onClick }} placement="bottom">
            <Space>
              <span>{userInfo.name}</span>
              <DownOutlined />
            </Space>
          </Dropdown>
        </div>
      );
    }
  };


  return (
    <Fragment>
      <header className="home-header">
        <div className="container">
          <div className="left" onClick={goToHome}>
            <img src={logo} alt="" />
            <span>尚医通 预约挂号统一平台</span>
          </div>
          <div className="right">
            <span>帮助中心</span>
            {
              isLogin()
            }
          </div>
        </div>
      </header>

      <Modal className="modal" title="用户登录" open={isModalOpen} onCancel={handleCancel} afterClose={afterClose}>
        <div className="left">
          <Form validateTrigger="onBlur" onFinish={onFinish} form={form}>
            <Form.Item name="phone" rules={[{ required: true, message: '请输入用户名' }]}>
              <Input size="large" prefix={<UserOutlined className="site-form-item-icon" />} placeholder="请输入用户名"></Input>
            </Form.Item>
            <Form.Item name="code" rules={[{ required: true, message: '请输入验证码' }]}>
              <Input size="large" prefix={<LockOutlined className="site-form-item-icon" />} placeholder="请输入验证码"></Input>
            </Form.Item>
            <Form.Item>
              <Button type="primary" onClick={getCode} disabled={start} danger>{renderCountdown()}</Button>
            </Form.Item>
            <Button type="primary" className="login" size="large" htmlType="submit" loading={isLoginLoading}>用户登录</Button>
          </Form>
        </div>
        <div className="right">
          <Tips></Tips>
        </div>
      </Modal>

    </Fragment>
  );
});

export default Header;
